<template>
  <CommonContainer title="还车结算">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="还车类别:" prop="returnCategory">
            <el-radio-group v-model="form.returnCategory" @change="calculateDeductionFees">
<!--                            <el-radio v-for="(dict, index) in dict.type.return_car_type" :key="dict.value"-->
<!--                                      :label="parseInt(dict.value)">-->
<!--                              <span>{{ dict.label }}</span>-->
<!--                            </el-radio>-->
              <el-radio :disabled="productTypeCode" :label="1"><span>提前还车</span></el-radio>
              <el-radio :disabled="!canDueDelivery||productTypeCode" :label="2"><span>到期还车</span></el-radio>
              <el-radio :disabled="!productTypeCode" :label="3"><span>租购还车</span></el-radio>
              <el-radio :label="4"><span>事故还车</span></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="form.returnCategory">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item :label="`${form.returnCategory==3?'过户时间':'还车时间'}`" prop="returnTime">
              <el-date-picker
                  style="width: 100%"
                  :picker-options="dynamicPickerOptions"
                  v-model="form.returnTime"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择时间"
                  @change="calculateDeductionFees"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="还车里程数(km):" prop="returnMileage">
              <el-input
                  v-model="form.returnMileage"
                  onkeyup="value=value.replace(/[^0-9]/g,'')"
                  placeholder="请输入还车里程数"
                  type="number"
                  @blur="blurReturnMileage">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="还车油量(%):" prop="returnFuel">
              <el-input v-model.number="form.returnFuel" onkeyup="value=value.replace(/[^0-9]/g,'')" placeholder="请输入还车油量" type="number"
                        oninput="form.returnFuel=form.returnFuel>100?100:form.returnFuel"
                        @blur="blurReturnFuel"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="已履行租期" prop="fulfilledLeaseTerm">
              <el-input disabled v-model="form.fulfilledLeaseTerm" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行驶里程数(km):" prop="drivingMileage" type="number">
              <el-input disabled v-model.number="form.drivingMileage" placeholder="输入还车里程后自动计算"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="油量差值(%):" prop="oilVolumeDiff" type="number">
              <el-input disabled v-model.number="form.oilVolumeDiff" placeholder="输入还车油量后自动计算"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8" v-if="form.returnCategory == 1">
            <el-form-item label="违约原因:" prop="defaultReason">
              <el-select v-model="form.defaultReason" placeholder="请选择违约原因" style="width: 100%">
                <el-option v-for="dict in dict.type.return_car_breach" :label="dict.label" :value="parseInt(dict.value)"
                           :key="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.returnCategory < 3">
            <el-form-item label="验车方式:" prop="vehicleInspectionMethod" required>
              <el-radio-group v-model="form.vehicleInspectionMethod">
                <el-radio v-for="(dict, index) in dict.type.vehicle_inspection_method" :key="dict.value"
                          :label="parseInt(dict.value)"><span>{{ dict.label }}</span></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <template v-if="form.returnCategory<3&&form.vehicleInspectionMethod==2">
            <el-col :span="8">
              <el-form-item label="联系人:" prop="thirdPartyContact">
                <el-input v-model="form.thirdPartyContact" placeholder="请输入联系人" maxlength="30"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人电话:" prop="thirdPartyContactPhone">
                <el-input v-model="form.thirdPartyContactPhone" placeholder="请输入联系人电话" maxlength="11"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检测城市:" prop="thirdPartyCityId">
                <el-select v-model="form.thirdPartyCityId" placeholder="请选择检测城市" style="width: 100%" filterable @change="changeCity">
                  <el-option v-for="city in cityList" :label="city.city" :value="city.cityId"
                             :key="city.cityId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="车辆存放地址:" prop="thirdPartyAddress">
                <div @click="chooseLocation">
                  <el-input v-model="form.thirdPartyAddress" placeholder="请选择车辆存放地址" maxlength="100" readonly></el-input>
                </div>

              </el-form-item>
            </el-col>

          </template>

          <el-col :span="24" v-if="form.returnCategory != 3">
            <el-form-item label="还车原因:" prop="reasonForReturningTheCar">
              <el-input type="textarea" placeholder="请输入还车原因" v-model="form.reasonForReturningTheCar" maxlength="500" :rows="4" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传还车单:" prop="returnSlip"  v-if="form.returnCategory != 3">
              <image-common :up-type="2" v-model="form.returnSlip" info="还车单" :limit="1"></image-common>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="还车附件:" prop="returnAccessories">
              <image-common :up-type="2" v-model="form.returnAccessories" info="上传附件" :limit="10"></image-common>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" v-if="form.returnCategory == 4">
          <el-col :span="24">
            <p class="subtitle">理赔信息</p>
          </el-col>
          <el-col :span="8">
            <el-form-item label="理赔承担方式:" prop="claimsMethod">
              <el-radio-group v-model="form.claimsMethod" @change="changeClaimsMethod">
                <el-radio v-for="(dict, index) in claimsLiabilityTypes" :key="dict.value"
                          :label="dict.value"><span>{{ dict.label }}</span></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item :label="`${form.claimsMethod==1?'客户理赔款':'保险理赔款'}`" prop="compensationClaims">
              <amount-input v-model.number="form.compensationClaims" placeholder="请输入理赔款"></amount-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="其他费用:" prop="otherFee">
              <amount-input v-model.number="form.otherFee" type="number" placeholder="请输入其他费用"></amount-input>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="form.returnCategory > 2">
          <el-row :gutter="10">
            <el-col :span="24">
              <p class="subtitle">违章信息</p>
            </el-col>
            <el-col :span="8">
              <el-form-item label="违章分数:" prop="violationScore">
                <!--              <el-input v-model.number="form.violationScore" type="number" onkeyup="value=value.replace(/[^\d||/.]/g,'')"-->
                <!--                        oninput="if(value){value=value.replace(/[^\d]/g,'')}  if(value>12){value=12}"-->
                <!--                        :maxlength="2"-->
                <!--                        :minlength="1" placeholder="请输入违章分数"></el-input>-->
                <number-input v-model.number="form.violationScore" :min="0" :max="12" placeholder="请输入违章分数"></number-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="违章费用:" prop="violationFee">
                <amount-input v-model.number="form.violationFee" type="number" placeholder="请输入违章费用"></amount-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="违章附件:" prop="violationAttachment">
                <image-common :up-type="2" v-model="form.violationAttachment" info="违章附件" :limit="10"></image-common>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <p class="subtitle">扣款费用</p>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车辆租金欠款金额:" prop="rentArrears">
                <amount-input v-model="form.rentArrears" placeholder="请输入车辆租金欠款金额"></amount-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="剩余租期:" prop="remainingLeaseTerm">
                <el-input v-model="form.remainingLeaseTerm" disabled ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="尾款:" prop="balancePayment">
                <amount-input v-model="form.balancePayment" placeholder="请输入尾款"></amount-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="加速折旧费:" prop="depreciation">
                <amount-input v-model.number="form.depreciation" placeholder="请输入加速折旧费"></amount-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="违约金:" prop="defaultDeduction">
                <amount-input v-model.number="form.defaultDeduction" placeholder="请输入违约金"></amount-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="超里程数(km):" prop="overMileage">
                <el-input v-model.number="form.overMileage" type="number" placeholder="请输入超里程数"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="超里程费:" prop="overMileageFee">
                <amount-input v-model.number="form.overMileageFee" placeholder="请输入超里程费"></amount-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <p class="subtitle">自定义扣款项</p>
            </el-col>
            <el-table
                :data="form.orderReturnDeduction"
                :header-cell-style="{ background: '#FAFAFA', color: '#000000' }" border>

              <el-table-column
                  align="center"
                  prop="deductionName"
                  label="扣款项名称"
                  min-width="180">
                <template v-slot="{row}">
                  <el-input v-model="row.deductionName" placeholder="扣款项名称" clearable/>
                </template>
              </el-table-column>
              <el-table-column
                  align="center"
                  prop="deductionAmount"
                  label="扣款金额"
                  min-width="180">
                <template v-slot="{row}">
                  <amount-input v-model="row.deductionAmount" placeholder="请输入扣款金额"/>
                </template>
              </el-table-column>
              <el-table-column
                  align="center"
                  prop="deductionReason"
                  label="扣款原因"
                  min-width="180">
                <template v-slot="{row}">
                  <el-input v-model="row.deductionReason" placeholder="请输入扣款原因" clearable/>
                </template>
              </el-table-column>

              <el-table-column
                  align="center"
                  prop="fieldDict"
                  label="操作"
                  fixed="right"
                  min-width="100">
                <template v-slot="{$index}">
                  <el-button type="danger" icon="el-icon-delete" circle @click="deleteDeductPayment($index)"></el-button>
                </template>
              </el-table-column>
              <template v-slot:append>
                <div class="flex-xy-center" style="height: 30px">
                  <el-button type="text" icon="el-icon-plus" @click="adddDuctPayments">添加扣款项</el-button>
                </div>
              </template>
            </el-table>
          </el-row>
        </template>
      </template>
    </el-form>
    <AMapLocation v-if="form.vehicleInspectionMethod==2" ref="amapLocation" :carNo="detailInfo.contractInformation.licensePlateNumber"
                  @chooseLocationSuccess="chooseLocationSuccess"></AMapLocation>
  </CommonContainer>
</template>

<script>
import {calculateDeductionFees, getCbsTestDeptList} from "@/api/returnCar/returnCar"
import AMapLocation from "@/views/returnCar/components/AMapLocation.vue";
import dayjs from "dayjs";
import NumberInput from "@/components/NumberInput/NumberInput.vue"; // ES 2015
export default {
  components: {NumberInput, AMapLocation},
  dicts: ['return_car_type', 'return_car_breach', 'vehicle_inspection_method'],
  props: {
    detailInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    const validateValue = (rule, value, callback) => {
      const outboundMileage = this.detailInfo?.outboundVehicleCondition?.outboundMileage || 0
      if (value < Number(outboundMileage)) {
        callback(new Error('还车里程数不能小于出库里程数'));
      } else {
        callback();
      }
    };
    return {
      claimsLiabilityTypes: [
        {
          label: '客户承担理赔',
          value: 1
        },
        {
          label: '保险理赔',
          value: 2
        }
      ],
      form: {
        returnCategory: null,
        fulfilledLeaseTerm: '--',
        returnTime: this.$dayjs().format('YYYY-MM-DD'),//还车时间
        returnMileage: null,//还车里程
        returnFuel: null,//还车油量
        drivingMileage: null,//行驶里程
        oilVolumeDiff: null,//油量差值
        vehicleInspectionMethod: 1,//验车方式
        defaultReason: null,//违约原因
        reasonForReturningTheCar: null,//还车原因
        returnAccessories: null,//还车附件
        claimsMethod: 2,//理赔方式:1客户理赔 2.保险理赔
        compensationClaims: this.detailInfo?.compensationClaims,//客户|保险理赔款
        otherFee: null,//理赔其他费用
        violationScore: null,//违章分数
        violationFee: null,//违章费用
        violationAttachment: null,//违章附件
        rentArrears: null,//车辆租金欠款金额
        remainingLeaseTerm: null,//剩余租期
        balancePayment: null,//尾款
        depreciation: null,//加速折旧费
        defaultDeduction: null,//违约金
        overMileage: null,//超里程数
        overMileageFee: null,//超里程费
        //自定义扣款项
        orderReturnDeduction: [],
        thirdPartyContact: null,//第三方检-联系人
        thirdPartyContactPhone: null,//第三方检-联系人电话
        thirdPartyCityId: null,//第三方检-检测城市id
        thirdPartyCityName: null,//第三方检-检测城市
        thirdPartyAddress: null,//第三方检-车辆存放地址
        longitude: null,
        latitude: null,
        returnSlip: null,//上传还车单

      },
      rules: {
        returnCategory:[
          {required: true, message: '请选择还车类别', trigger: 'change'},
        ],
        returnTime: [
          {required: true, message: '请选择还车时间', trigger: 'change'},
        ],
        returnMileage: [
          {required: true, message: '请输入还车里程数', trigger: 'change'},
          {validator: validateValue, trigger: 'blur'}
        ],
        returnFuel: [
          {required: true, message: '请输入还车油量', trigger: 'blur'},
          {
            pattern: /^([1-9][0-9]{0,1}|100)$/,
            message: "请输入1-100的整数",
            trigger: "blur"
          }
        ],
        // returnAccessories: [
        //   {required: true, message: '请上传还车附件', trigger: 'change'},
        // ],
        defaultReason: [
          {required: true, message: '请选择违约原因', trigger: 'change'},
        ],
        vehicleInspectionMethod: [
          {required: true, message: '请选择验车方式', trigger: 'change'},
        ],
        violationScore: [
          {
            pattern: /^([0-9][1-2]{0,1})$/,
            message: "请输入0-12的整数",
            trigger: "blur"
          }
        ],
        thirdPartyContact: [
          {required: false, message: '请输入联系人', trigger: 'blur'},
        ],
        thirdPartyContactPhone: [
          {required: false, message: '请输入联系人电话', trigger: 'blur'},
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        thirdPartyCityId: [
          {required: false, message: '请选择检测城市', trigger: 'change'},
        ],
        thirdPartyAddress: [
          {required: true, message: '请选择车辆存放地址', trigger: 'change'},
        ],
        returnSlip: [
          {required: true, message: '请上传还车单', trigger: 'change'},
        ],

        violationAttachment: [
          {required: true, message: '请上传违章附件', trigger: 'blur'},
        ],
      },
      cityList: [],
      returnCarType: []

    }
  },
  computed: {
    // fulfilledLeaseTerm(){
    //   let outboundDate = this.detailInfo?.outboundVehicleCondition.outboundDate;
    //   const date1 = new Date(outboundDate);
    //   const date2 = new Date(this.form.returnTime);
    //   if(!date1||!this.form.returnTime){
    //     return "--"
    //   }
    //   let months = (date2.getFullYear() - date1.getFullYear()) * 12;
    //   months -= date1.getMonth();
    //   months += date2.getMonth();
    //   const dateDiff = date2.getDate() - date1.getDate();
    //   if (dateDiff < 0) {
    //     months--;
    //   }
    //   if(months<0||(months===0&&dateDiff<0)){
    //     return "0日"
    //   }else{
    //     if(months===0){
    //       return `${dateDiff > 0 ? dateDiff : 1}日`;
    //     }else{
    //       return `${months}月${dateDiff > 0 ? dateDiff : 0}日`;
    //     }
    //   }
    // },
    dynamicPickerOptions() {
      const returnCategory = this.form.returnCategory
      // 使用计算属性来根据父组件传来的 prop 计算 picker-options
      let disableBeforeDate = dayjs(this.detailInfo?.outboundVehicleCondition.outboundDate).format('YYYY-MM-DD');
      return {
        disabledDate(time) {
          const selectedDate = dayjs(time).format('YYYY-MM-DD');
          // 禁用 disableBeforeDate 之前的所有日期
          return dayjs(selectedDate).isBefore(disableBeforeDate);
        }
      }
    },
    canDueDelivery() {
      return this.detailInfo.contractInformation?.canDueDelivery || false;
    },
    productTypeCode() {
      const productTypeCode = this.detailInfo.contractInformation?.productTypeCode
        return (productTypeCode == 2 || productTypeCode == 4) ;
    }
  },
  methods: {

    chooseLocation() {
      this.$refs.amapLocation.show(this.form.thirdPartyCityName)
    },
    chooseLocationSuccess(locationInfo) {
      this.form.thirdPartyAddress = locationInfo?.address;
      this.form.longitude = locationInfo?.kqLongitude;
      this.form.latitude = locationInfo?.kqLatitude;
    },
    getCityList() {
      getCbsTestDeptList().then(res => {
        this.cityList = res.data || [];
      })
    },
    //检测城市发生改变
    changeCity(val) {
      const cityObj = this.cityList.find(item => item.cityId == val)
      this.form.thirdPartyCityName = cityObj.city;
    },
    // 理赔方式修改
    changeClaimsMethod(val) {
      if (val == 1) {
        this.form.compensationClaims = null;//理赔款
      } else if (val == 2) {
        this.form.compensationClaims = this.detailInfo?.compensationClaims;//保险理赔款
        this.calculateDeductionFees()
      }
    },
    // 计算行驶里程
    blurReturnMileage() {
      let returnMileage = Number(this.form.returnMileage)
      let outboundMileage = Number(this.detailInfo.outboundVehicleCondition.outboundMileage)
      this.form.drivingMileage = returnMileage - outboundMileage
      this.calculateDeductionFees()
    },
    //计算油量差值
    blurReturnFuel() {
      this.form.returnFuel = Number(this.form.returnFuel);
      // if (this.form.returnFuel > 100) {
      //     this.form.returnFuel = 100;
      // } else if (this.form.returnFuel < 1) {
      //     this.form.returnFuel = 1;
      // }
      this.form.oilVolumeDiff = Number(this.form.returnFuel) - Number(this.detailInfo?.outboundVehicleCondition?.outboundOilVolume)
      this.calculateDeductionFees()
    },
    adddDuctPayments() {
      const obj = {
        deductionName: null,
        deductionAmount: null,
        deductionReason: null
      }
      this.form.orderReturnDeduction.push(obj)
    },
    deleteDeductPayment(index) {
      this.form.orderReturnDeduction.splice(index, 1)
    },

    // 计算扣款费用
    calculateDeductionFees() {
      if (this.form.returnCategory > 2) {
        calculateDeductionFees({
          orderNumber: this.detailInfo.orderNumber,
          outboundMileage: this.detailInfo.outboundMileage,
          outboundFuel: this.detailInfo.outboundFuel,
          returnCategory: this.form.returnCategory,
          returnTime: this.form.returnTime,
          returnMileage: this.form.returnMileage,
          returnFuel: this.form.returnFuel
        }).then(res => {
          const data = res.data;
          this.form.fulfilledLeaseTerm = data?.fulfilledLeaseTerm
          this.form.compensationClaims = data?.compensationClaims;
          this.form.otherFee = data?.otherFee;
          this.form.rentArrears = data?.rentArrears;
          this.form.depreciation = data?.depreciation;
          this.form.remainingLeaseTerm = data?.remainingLeaseTerm
          this.form.defaultDeduction = data?.defaultDeduction
          this.form.defaultReduction = data?.defaultReduction
          this.form.overMileage = data?.overMileage
          this.form.overMileageFee = data?.overMileageFee
          this.form.balancePayment = data?.balancePayment
          this.form.violationScore = data?.violationScore
          this.form.violationFee = data?.violationFee
        })
      }else{
        calculateDeductionFees({
          orderNumber: this.detailInfo.orderNumber,
          outboundMileage: this.detailInfo.outboundMileage,
          outboundFuel: this.detailInfo.outboundFuel,
          returnCategory: this.form.returnCategory,
          returnTime: this.form.returnTime,
          returnMileage: this.form.returnMileage,
          returnFuel: this.form.returnFuel
        }).then(res => {
          const data = res.data;
          this.form.fulfilledLeaseTerm = data?.fulfilledLeaseTerm
        })
      }
    },

    saveForm() {
      let flag = false
      this.$refs['form'].validate((valid) => {
        if (valid) {
          flag = true
          if (this.form.orderReturnDeduction && this.form.orderReturnDeduction.length > 0) {
            this.form.orderReturnDeduction.every((item) => {
              if (this.isNull(item.deductionName)) {
                this.$message.error('请完善扣款项名称')
                flag = false
                return
              } else if (this.isNull(item.deductionAmount)) {
                this.$message.error('请完善扣款金额')
                flag = false
                return
              }
            })
          }
        } else {
          flag = false
        }
      })
      if (flag) {
        console.log('还车结算-----', this.form)
        return this.form
      }
    },

  },
  watch: {
    detailInfo: {
      immediate: true,
      deep: true,
      handler(val) {
        if(this.detailInfo.id){
          this.form={
            ...this.detailInfo
          }
          this.form.oilVolumeDiff = Number(this.form.returnFuel) - Number(this.detailInfo?.outboundVehicleCondition?.outboundOilVolume)
        }
      }
    }
  },
  mounted() {

    this.getCityList()
  },
  created() {

  }

}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/variables.scss";

.subtitle {
  font-size: 14px;
  font-weight: bold;
  color: #333333;

  &::before {
    display: inline-block;
    content: '';
    width: 8px;
    height: 8px;
    border-radius: 4px;
    background-color: $primary;
    margin-right: 5px;
    position: relative;
    top: -1px;
  }
}

::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}

.el-form-item {
  margin-bottom: 15px;
  width: 70%;
}
</style>
